#!/usr/bin/env python3
"""
MongoDB连接管理器使用示例
演示如何连接MongoDB、创建索引、保存和查询数据
"""

import asyncio
import logging
from datetime import datetime
from typing import List

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 导入自定义模块
from database.connection_manager import MongoConnectionManager
from utils.database_helper import DatabaseHelper
from models.article import ArticleModel

async def test_database_connection():
    """测试数据库连接"""
    print("=" * 50)
    print("测试MongoDB连接管理器")
    print("=" * 50)
    
    # 创建连接管理器实例
    manager = MongoConnectionManager(
        host="localhost",
        port=27017,
        database_name="site_evaluation"
    )
    
    try:
        # 1. 测试连接
        print("\n1. 连接到MongoDB...")
        connected = await manager.connect()
        
        if not connected:
            print("❌ 连接失败！请确保MongoDB在localhost:27017运行")
            return
        
        print("✅ 连接成功！")
        
        # 2. 获取连接状态
        print("\n2. 获取连接状态...")
        status = await manager.get_connection_status()
        print(f"   连接状态: {status['connected']}")
        print(f"   服务器地址: {status['host']}:{status['port']}")
        print(f"   数据库名: {status['database']}")
        if 'server_version' in status:
            print(f"   MongoDB版本: {status['server_version']}")
        
        # 3. 创建索引
        print("\n3. 创建数据库索引...")
        indexes_created = await manager.create_indexes("articles")
        if indexes_created:
            print("✅ 索引创建成功")
        else:
            print("❌ 索引创建失败")
        
        # 4. 测试数据库操作
        await test_database_operations(manager)
        
    except Exception as e:
        print(f"❌ 测试过程中出错: {e}")
    finally:
        # 5. 断开连接
        print("\n5. 断开数据库连接...")
        await manager.disconnect()
        print("✅ 连接已断开")

async def test_database_operations(manager: MongoConnectionManager):
    """测试数据库基本操作"""
    print("\n4. 测试数据库操作...")
    
    # 创建数据库助手实例
    db_helper = DatabaseHelper()
    
    # 创建示例文章
    sample_articles = [
        ArticleModel(
            url="https://example.com/tech-article-1",
            title="人工智能的未来发展趋势",
            content="人工智能技术正在快速发展，预计在未来几年将在各个行业产生深远影响..." * 5,
            summary="探讨AI技术的发展趋势",
            author="张三",
            publish_date=datetime.now(),
            industry_keyword="科技",
            source_domain="example.com",
            content_length=200,
            language="zh",
            meta_description="AI发展趋势分析",
            keywords=["人工智能", "科技", "未来"],
            status="success",
            error_message=None
        ),
        ArticleModel(
            url="https://example.com/finance-article-1",
            title="数字货币市场分析",
            content="数字货币市场在2024年展现出新的发展趋势，投资者需要关注以下几个方面..." * 5,
            summary="分析数字货币市场现状",
            author="李四",
            publish_date=datetime.now(),
            industry_keyword="金融",
            source_domain="example.com",
            content_length=250,
            language="zh",
            meta_description="数字货币市场分析",
            keywords=["数字货币", "金融", "投资"],
            status="success",
            error_message=None
        )
    ]
    
    # 4.1 保存文章
    print("   4.1 保存示例文章...")
    for i, article in enumerate(sample_articles):
        success = await db_helper.save_article(article)
        if success:
            print(f"   ✅ 文章 {i+1} 保存成功")
        else:
            print(f"   ⚠️  文章 {i+1} 已存在或保存失败")
    
    # 4.2 查询文章
    print("   4.2 查询文章...")
    tech_articles = await db_helper.get_articles_by_industry("科技", limit=5)
    print(f"   找到 {len(tech_articles)} 篇科技类文章")
    
    finance_articles = await db_helper.get_articles_by_industry("金融", limit=5)
    print(f"   找到 {len(finance_articles)} 篇金融类文章")
    
    # 4.3 获取统计信息
    print("   4.3 获取统计信息...")
    stats = await db_helper.get_article_statistics()
    print(f"   总文章数: {stats.get('total_articles', 0)}")
    print(f"   成功文章数: {stats.get('success_articles', 0)}")
    print(f"   成功率: {stats.get('success_rate', 0)}%")
    
    if stats.get('industry_distribution'):
        print("   各行业文章分布:")
        for industry, count in stats['industry_distribution'].items():
            print(f"     {industry}: {count}篇")
    
    # 4.4 检查URL是否存在
    print("   4.4 检查URL是否存在...")
    url_exists = await db_helper.check_url_exists("https://example.com/tech-article-1")
    print(f"   URL存在检查: {'存在' if url_exists else '不存在'}")

async def demonstrate_connection_features():
    """演示连接管理器的高级功能"""
    print("\n" + "=" * 50)
    print("演示连接管理器高级功能")
    print("=" * 50)
    
    manager = MongoConnectionManager()
    
    try:
        # 连接并确保连接可用
        print("1. 确保数据库连接...")
        connection_ok = await manager.ensure_connection()
        print(f"   连接状态: {'✅ 正常' if connection_ok else '❌ 失败'}")
        
        # 使用上下文管理器操作数据库
        print("2. 使用上下文管理器操作数据库...")
        async with manager.get_collection("test_collection") as collection:
            # 插入测试数据
            test_doc = {"test": "data", "timestamp": datetime.now()}
            result = await collection.insert_one(test_doc)
            print(f"   插入测试文档，ID: {result.inserted_id}")
            
            # 查询测试数据
            found_doc = await collection.find_one({"_id": result.inserted_id})
            if found_doc:
                print("   ✅ 成功查询到测试文档")
            
            # 删除测试数据
            await collection.delete_one({"_id": result.inserted_id})
            print("   ✅ 清理测试数据完成")
        
    except Exception as e:
        print(f"❌ 演示过程中出错: {e}")
    finally:
        await manager.disconnect()

def main():
    """主函数"""
    print("MongoDB连接管理器示例程序")
    print("请确保MongoDB服务在localhost:27017端口运行")
    print()
    
    try:
        # 运行基本连接测试
        asyncio.run(test_database_connection())
        
        # 运行高级功能演示
        asyncio.run(demonstrate_connection_features())
        
        print("\n" + "=" * 50)
        print("✅ 所有测试完成！")
        print("=" * 50)
        
    except KeyboardInterrupt:
        print("\n用户中断程序")
    except Exception as e:
        print(f"\n❌ 程序运行出错: {e}")

if __name__ == "__main__":
    main() 